package com.levenx.config;

import com.levenx.properties.DataBaseProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

@Configuration
@EnableJpaRepositories(basePackages = {"com.levenx"})
@EnableTransactionManagement
public class JPAConfig {

    @Autowired
    private DataBaseProperties dataBaseProperties;

    //建立数据源
    @Bean
    public DataSource dataSource() {
        return DataSourceBuilder.create()
                .driverClassName(dataBaseProperties.getDriverClassName())
                .url(dataBaseProperties.getUrl())
                .username(dataBaseProperties.getUsername())
                .password(dataBaseProperties.getPassword())
                .build();
    }

    //实体类的管理工厂
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        //实例化jpa适配器，由于使用的是hibernate所以用hibernatejpavendor
        HibernateJpaVendorAdapter japVendor = new HibernateJpaVendorAdapter();
        //不生成sql
        japVendor.setGenerateDdl(true);
        //实例化管理工厂
        LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactory.setDataSource(dataSource());
        entityManagerFactory.setJpaVendorAdapter(japVendor);
        //设置扫描包名
        entityManagerFactory.setPackagesToScan("com.levenx");
        return entityManagerFactory;
    }

    //事务管理
    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
        //实例化
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory);
        return transactionManager;
    }
}
